<?php
class Grid extends VmView
{
    public $filter;
    public $rpp;
    public $recordCount;
    public $pageCount;
    public $page;
    public $sort;
    public $order;

	public $message;

	protected $condition;
	protected $orderby;

    protected function ProcessRequest()
    {
        try
        {
            $action = RequestHandler::Get('action');
            if ($action)
            {
                $selected = RequestHandler::Get('selected');
                if (isset($selected['all']))
                    unset($_REQUEST['selected']['all']);

                switch ($action)
                {
                    case 'Save':
                        $this->Save();
                        break;
                    case 'Delete':
                        $this->Delete();
                        break;
                    case 'UpdateParentId':
                        $this->viewModel->UpdateParentId(RequestHandler::Get('drag'), RequestHandler::Get('drop'));
                        break;
                    default:
                        $reflect = new ReflectionMethod($this->viewModel, $action);
                        $params = $reflect->getParameters();
                        $args = array();
                        foreach ($params as $param)
                        {
                            $args[] = RequestHandler::Get($param->name);
                        }
                        $reflect->invokeArgs($this->viewModel, $args);
                        break;
                }
            }
        }
        catch (Exception $ex)
        {
            MessageBase::Exception($ex);
        }
    }

    public function Refresh()
	{
		$this->filter 		= RequestHandler::GetFilter();
		$this->condition 	= $this->GetCondition();
		$this->rpp 			= $this->GetRpp();
		$this->page 		= $this->GetPage();
        $this->sort         = RequestHandler::Get('sort');
        $order              = RequestHandler::Get('order');
        $this->order        = $order ? $order : 'asc';
		$this->orderby 		= $this->GetOrderBy();
        $this->recordCount  = 0;
        $this->data         = $this->GetData();
        $this->pageCount    = $this->GetPagecount();
	}

	public function GetData()
	{
		return $this->viewModel->Find($this->condition, $this->GetFieldList(), $this->orderby, $this->rpp, $this->page, $this->recordCount);
	}

   	protected function GetFieldList()
	{
        $enabled_fields = $this->GetEnabledFields();
        $fields = array();
        foreach ($enabled_fields as $field)
        {
            $fields[] = $field->GetSqlName();
        }
		$pk = $this->viewModel->GetPrimaryKey();
		if ($pk && !array_key_exists($pk, $enabled_fields))
        {
            if (array_key_exists($pk, $this->fields))
                $fields[] = $this->fields[$pk]->GetSqlName();
        }
		return $fields;
	}

	protected function GetCondition()
	{
		if (empty($this->filter)) return null;

		$conditions = new SqlQuery();
		foreach($this->filter as $k => $value)
		{
			if (!is_null($value))
			{
				$field = $this->GetField($k);
                $type = $field->type;
                $model_name = $field->modelName;

                $key = String::ContainsAny(array('.', '(', ' '), $k) && $model_name ? $k : "$model_name.$k";

				if ($field->IsString())
				{
                    if (String::Contains('=', $value))
                    {
                        $type = AppConfig::GetInstance()->SQL_MIX;
                        $sql[] = "$key @$key";
                    }
                    else if ($field->filterExact || $field->IsSelectBox() || $field->IsGridSelect() || !$field->enabled)
                    {
                        $sql[] = "$key = @$key";
                    }
                    else
                    {
                        $value = "%$value%";
                        $sql[] = "$key LIKE @$key";
                    }
				}
				else if ($field->IsDatetime() && String::ContainsAny('BETWEEN, <, >', $value))
				{
					$type = AppConfig::GetInstance()->SQL_MIX;
					$sql[] = "$key @$key";
				}
				else if ($field->IsNumeric() && String::ContainsAny('<, >', $value))
				{
					$type = AppConfig::GetInstance()->SQL_MIX;
					$sql[] = "$key @$key";
				}
				else
				{
					$sql[] = "$key = @$key";
				}
				$conditions->Add($key, $value, $type);
			}
		}
		if (!empty($sql))
			$conditions->sql = implode(' AND ', $sql);

		return $conditions;
	}

    protected function GetOrderBy()
    {
        return $this->sort ? "{$this->sort} {$this->order}" : null;
    }

    public function GetViewModel()
    {
        return $this->viewModel;
    }

    protected function GetPagecount()
    {
        return ceil($this->recordCount/$this->rpp);
    }

    protected function GetRpp()
    {
        $key = $this->id ? $this->id : $this->model->GetTableName();
        $rpp = RequestHandler::Get('limit');
        if ($rpp)
            GridConfig::GetInstance()->SetRpp($key, $rpp);
        else
            $rpp = GridConfig::GetInstance()->GetRpp($key);
        return $rpp;
    }

    protected function GetPage()
    {
        $page = RequestHandler::Get('page');
        return $page>0 ? $page : 1;
    }

    protected function GetModelClassName()
    {
        return 'VmViewModel';
    }
}
?>